package com.rongshu.sendmessage.fragment;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.Image;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.alibaba.fastjson.JSON;
import com.facebook.drawee.backends.pipeline.Fresco;
import com.facebook.drawee.interfaces.DraweeController;
import com.facebook.drawee.view.SimpleDraweeView;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.rongshu.sendmessage.R;
import com.rongshu.sendmessage.activity.AboutActivity;
import com.rongshu.sendmessage.activity.KeFuActivity;
import com.rongshu.sendmessage.activity.MoreMessageActivity;
import com.rongshu.sendmessage.activity.MyHomeActivity;
import com.rongshu.sendmessage.activity.MyMessageActivity;
import com.rongshu.sendmessage.activity.PayLogActivity;
import com.rongshu.sendmessage.activity.PermissionActvity;
import com.rongshu.sendmessage.activity.PlayVideoWebViewActivity;
import com.rongshu.sendmessage.activity.SettingActivity;
import com.rongshu.sendmessage.activity.WebViewActivity;
import com.rongshu.sendmessage.activity.WebYinSiActivity;
import com.rongshu.sendmessage.activity.YiJianActivity;
import com.rongshu.sendmessage.base.BaseFragment;
import com.rongshu.sendmessage.base.MyApplication;
import com.rongshu.sendmessage.bean.UserInfoBean;
import com.rongshu.sendmessage.util.ClientPublicParamUtil;
import com.rongshu.sendmessage.util.DialogUtil;
import com.rongshu.sendmessage.util.StringUtils;
import com.rongshu.sendmessage.util.ToastUtils;
import com.rongshu.sendmessage.util.httpUtil.Common;
import com.rongshu.sendmessage.util.httpUtil.HYContent;
import com.rongshu.sendmessage.util.httpUtil.IModel;
import com.rongshu.sendmessage.view.TitileLayout;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

import static com.rongshu.sendmessage.util.DialogUtil.hideProgress;

public class MyFragment extends BaseFragment implements View.OnClickListener {
    private TextView tv_name;
    private Intent mIntent;
    private Context mContext;
    private SimpleDraweeView sdv_head;
    private String userId;
    private TextView tv_dingzhi_number,tv_fabu_number;
    private TextView tv_gexing;
    private BordCars bordCars;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext=getContext();
        IntentFilter filter=new IntentFilter();
        filter.addAction("com.huoyun.tabbar.itemclick");
        bordCars = new BordCars();
        Objects.requireNonNull(getActivity()).registerReceiver(bordCars,filter);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Objects.requireNonNull(getActivity()).unregisterReceiver(bordCars);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        View rootView = inflater.inflate(R.layout.my_fragment, null);
        initView(rootView);
        userId= MyApplication.mSettings.getString(HYContent.UserId,"");
        initData();
        return rootView;
    }

    private void initData() {
        DialogUtil.showProgress(mContext);
        Map<String, String> param = new HashMap<>();
//        String userId= MyApplication.mSettings.getString(HYContent.UserId,"");
        param.put("userId",userId);
        param.put("clientPublicParam", ClientPublicParamUtil.getPublicParams(mContext));
        String url= new HYContent().MY_HOME_DATA_URL;
        OkGo.<String>post(url).params(param).execute(new StringCallback() {
            @Override
            public void onSuccess(Response<String> response) {
                IModel.AjaxResult jr = new IModel.AjaxResult(response.body(),false);
                final int code = jr.getCode();
                if(code > 0) {
                    hideProgress();
                    UserInfoBean bean = JSON.parseObject(JSON.toJSONString(jr.getData()), UserInfoBean.class);
                    setData(bean);
                }else{
                    ToastUtils.show(mContext,jr.getMsg());
                    hideProgress();
                }
            }
            @Override
            public void onError(Response<String> response) {
                ToastUtils.show(mContext,"操作失败");
                hideProgress();
            }
        });
    }

    private void setData(UserInfoBean bean) {
        DraweeController controller= Fresco.newDraweeControllerBuilder()
                .setUri(bean.getImgUrl())
//                .setTapToRetryEnabled(true)
                .setOldController(sdv_head.getController())
                .build();
        sdv_head.setController(controller);
        tv_name.setText(bean.getNick());
        tv_gexing.setText(bean.getPersonalizedSignature());
        tv_dingzhi_number.setText(StringUtils.isEmpty(bean.getUnreadPush())?"0次":bean.getUnreadPush()+"次");
        tv_fabu_number.setText(StringUtils.isEmpty(bean.getOrdinarySmsShowMinuteTime())?"0分钟":bean.getOrdinarySmsShowMinuteTime()+"分钟");
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode==HYContent.REQUSET_CODE){

            initData();
        }
    }


    private void initView(View rootView) {
        rootView.findViewById(R.id.ll_pay_log).setOnClickListener(this);
        rootView.findViewById(R.id.ll_my_home).setOnClickListener(this);
        rootView.findViewById(R.id.ll_shezhi).setOnClickListener(this);
        rootView.findViewById(R.id.ll_kefu).setOnClickListener(this);
        rootView.findViewById(R.id.ll_jianyi).setOnClickListener(this);
        rootView.findViewById(R.id.ll_bangzhu).setOnClickListener(this);
        rootView.findViewById(R.id.dingzhi_fabu).setOnClickListener(this);
        rootView.findViewById(R.id.my_fabu).setOnClickListener(this);
        rootView.findViewById(R.id.ll_guanyu).setOnClickListener(this);

        rootView.findViewById(R.id.ll_fuwu).setOnClickListener(this);
        rootView.findViewById(R.id.ll_zhuxiao).setOnClickListener(this);
        rootView.findViewById(R.id.ll_yinsi).setOnClickListener(this);
        rootView.findViewById(R.id.ll_quanxian).setOnClickListener(this);
        rootView.findViewById(R.id.ll_chexiao).setOnClickListener(this);
        tv_name = rootView.findViewById(R.id.tv_name);
        tv_dingzhi_number = rootView.findViewById(R.id.tv_dingzhi_number);
        tv_gexing = rootView.findViewById(R.id.tv_gexing);
        tv_fabu_number = rootView.findViewById(R.id.tv_fabu_number);
        sdv_head = rootView.findViewById(R.id.sdv_head);
        
        
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.ll_pay_log) {
            mIntent = new Intent(getContext(), PayLogActivity.class);
            startActivity(mIntent);
        } else if (v.getId() == R.id.ll_my_home) {
            mIntent = new Intent(getContext(), MyHomeActivity.class);
            startActivityForResult(mIntent,HYContent.REQUSET_CODE);
        }  else if (v.getId() == R.id.ll_shezhi) {
            mIntent = new Intent(getContext(), SettingActivity.class);
            startActivity(mIntent);
        } else if (v.getId() == R.id.ll_kefu) {
            mIntent = new Intent(getContext(), KeFuActivity.class);
            startActivity(mIntent);
        } else if (v.getId() == R.id.ll_jianyi) {
            mIntent = new Intent(getContext(), YiJianActivity.class);
            startActivity(mIntent);
        } else if (v.getId() == R.id.ll_bangzhu) {
            initHelpData();
        }else if (v.getId() == R.id.dingzhi_fabu) {
            mIntent=new Intent(mContext, MyMessageActivity.class);//MoreMessageActivity
            mIntent.putExtra("source","dingzhi");
            startActivity(mIntent);
        }else if (v.getId() == R.id.my_fabu) {
            mIntent=new Intent(mContext, MyMessageActivity.class);//MoreMessageActivity
            mIntent.putExtra("source","my");
            startActivity(mIntent);
        }else if (v.getId() == R.id.ll_guanyu) {
            mIntent=new Intent(mContext, WebViewActivity.class);
            mIntent.putExtra("source","guanyu");
            startActivity(mIntent);
        }else if (v.getId()==R.id.ll_fuwu){
            mIntent=new Intent(mContext, WebYinSiActivity.class );
            mIntent.putExtra("souce","fuwu");
            startActivity(mIntent);
        }else if(v.getId()==R.id.ll_yinsi){
            mIntent=new Intent(mContext, WebYinSiActivity.class );
            mIntent.putExtra("souce","yinsi");
            startActivity(mIntent);
        }else if(v.getId()==R.id.ll_quanxian){
            mIntent=new Intent(mContext, PermissionActvity.class );
            startActivity(mIntent);
        }else if (v.getId()==R.id.ll_zhuxiao){
            DialogUtil.showTextDialog(mContext,"注销","您确定要注销该账户吗？",false,new DialogUtil.OnDialogEvent<Void>(){
                @Override
                public void onPositiveButtonClick(Void unused) {
                    super.onPositiveButtonClick(unused);
                    zhuxiao();
                }
            });
        }else if (v.getId()==R.id.ll_chexiao){
            DialogUtil.showTextDialog(mContext,"权限","您确定要撤销隐私政策和服务协议吗？撤销后，将无法使用App，并退出应用!",false,new DialogUtil.OnDialogEvent<Void>(){
                @Override
                public void onPositiveButtonClick(Void unused) {
                    super.onPositiveButtonClick(unused);
                    MyApplication.editor.putBoolean(MyApplication.IS_TONGYI_XIEYI,false);
                    MyApplication.editor.putString(HYContent.UserId,"");
                    MyApplication.editor.putBoolean(HYContent.IS_LOGIN,false);
                    MyApplication.editor.commit();
                    getActivity().finish();
                }
            });
        }
    }

    private void zhuxiao() {
        DialogUtil.showProgress(mContext);
        Map<String, String> param = new HashMap<>();
        String userId = MyApplication.mSettings.getString(HYContent.LOGIN_NAME, "");
        param.put("userId", userId);
        param.put("clientPublicParam", ClientPublicParamUtil.getPublicParams(mContext));
        String url = new HYContent().ZHUXIAO_URL;
        OkGo.<String>post(url).params(param).tag("ZHUXIAO_URL").execute(new StringCallback() {
            @Override
            public void onSuccess(Response<String> response) {
                IModel.AjaxResult jr = new IModel.AjaxResult(response.body(), false);
                final int code = jr.getCode();
                if (code > 0) {
                    hideProgress();
                    MyApplication.editor.putBoolean(HYContent.IS_LOGIN,false);
                    MyApplication.editor.putString(HYContent.UserId,"");
                    MyApplication.editor.commit();
                    getActivity().finish();
                } else {
                    ToastUtils.show(mContext, jr.getMsg());
                    hideProgress();
                }
            }

            @Override
            public void onError(Response<String> response) {
                ToastUtils.show(mContext, "操作失败");
                hideProgress();
            }
        });
    }

    private void initHelpData() {
        mIntent=new Intent(getContext(), WebViewActivity.class);
        mIntent.putExtra("source","help");
//        http://39.103.223.73/tckx
//        mIntent.putExtra("webUrl",new Common().getRequstUrl()+"/bz.html");
        startActivity(mIntent);
//        DialogUtil.showProgress(mContext);
//        Map<String, String> param = new HashMap<>();
//        String userId = MyApplication.mSettings.getString(HYContent.LOGIN_NAME, "");
//        param.put("username", userId);
//        param.put("clientPublicParam", ClientPublicParamUtil.getPublicParams(mContext));
//        String url = new HYContent().GET_USER_HEAD_URL;
//        OkGo.<String>post(url).params(param).tag("GET_USER_HEAD_URL").execute(new StringCallback() {
//            @Override
//            public void onSuccess(Response<String> response) {
//                IModel.AjaxResult jr = new IModel.AjaxResult(response.body(), false);
//                final int code = jr.getCode();
//                if (code > 0) {
//                    hideProgress();
//
//
//                } else {
//                    ToastUtils.show(mContext, jr.getMsg());
//                    hideProgress();
//                }
//            }
//
//            @Override
//            public void onError(Response<String> response) {
//                ToastUtils.show(mContext, "操作失败");
//                hideProgress();
//            }
//        });
    }
    class BordCars extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (2==intent.getIntExtra("position",0))
                initData();
        }
    }
}
